package com.lishe.lishe.lishe.module.shopingcart.activity;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.lishe.lishe.R;
import com.lishe.lishe.lishe.base.BaseActivity;
import com.lishe.lishe.lishe.bean.AddressObject;
import com.lishe.lishe.lishe.bean.ShoppingCartObject;
import com.lishe.lishe.lishe.common.Globals;
import com.lishe.lishe.lishe.module.mall.activity.MallGoodsActivity;
import com.lishe.lishe.lishe.module.me.activity.AddressManageActivity;
import com.lishe.lishe.lishe.module.myorder.activity.ConfirmOrderActivity;
import com.lishe.lishe.lishe.module.myorder.bean.BusinessObject;
import com.lishe.lishe.lishe.module.myorder.bean.GoodObject;
import com.lishe.lishe.lishe.module.myorder.bean.OrderObject;
import com.lishe.lishe.lishe.module.myorder.http.HttpMyOrder;
import com.lishe.lishe.lishe.module.shopingcart.adapter.ShoppingCartAdapter;
import com.lishe.lishe.lishe.module.shopingcart.adapter.ShoppingCartAdapter0;
import com.lishe.lishe.lishe.module.shopingcart.http.HttpShopppingCart;
import com.lishe.lishe.lishe.module.shopingcart.shoppingcartpresenter.ShoppingCartPresenter;
import com.lishe.lishe.lishe.pulltorefresh.PullToRefreshBase;
import com.lishe.lishe.lishe.pulltorefresh.PullToRefreshListView;
import com.lishe.lishe.lishe.utils.LoadingUtils;
import com.lishe.lishe.retrofit.DataResponseListener;
import com.loopj.android.http.AsyncHttpResponseHandler;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import cz.msebera.android.httpclient.Header;

/**
 * Created by lwa on 2017/8/10.
 * 购物车
 */

public class ShoppingCartActivity extends BaseActivity implements View.OnClickListener {
    private static String TAG = ShoppingCartActivity.class.getSimpleName();
    private Button btnBack;
    private Button btnBalance;
    private ImageView checkAll;
    private TextView texTitle;
    private TextView texReceiveAddress;
    private TextView texTotalMoney;
    private PullToRefreshListView listview;
    private RelativeLayout emptyLayout;
    private LinearLayout addressLayout;
    private LinearLayout buttomLayout;
    private ShoppingCartAdapter adapter;
    private ShoppingCartObject shoppingCartObject = new ShoppingCartObject();//购物车对象
    private boolean isCheckAll = false;
    private double payMoney = 0;//选中商品的总金额
    private int goodsCount = 0;//选中商品的数量
    private AddressObject addressObject = new AddressObject();//地址信息
    private OrderObject orderObject = new OrderObject();//创建订单对象传到payactivity
    private boolean isCallbaclShow = false;//title 的回退键是否显示
    private String token;
    private boolean isToast = true;//是否吐司


    public static void jump(Activity activity, boolean isCallbaclShow) {
        Intent intent = new Intent(activity, ShoppingCartActivity.class);
        intent.putExtra("isCallbaclShow", isCallbaclShow);
        activity.startActivity(intent);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shopping_cart);
        token = Globals.getToken();
        adapter = new ShoppingCartAdapter(ShoppingCartActivity.this, shoppingCartObject);
        isCallbaclShow = getIntent().getBooleanExtra("isCallbaclShow", isCallbaclShow);
        regisBrocastReciver();
        initView();
        getReceiveAddress();
        getShopppingCart(false);
    }


    @Override
    protected void onResume() {
        Log.e(TAG + "onResume", "haha ");
        super.onResume();
    }

    @Override
    protected void onStop() {
        Log.e(TAG = "onStop", "haha ");
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(receiver!=null){
            unregisterReceiver(receiver);
            receiver=null;
        }
    }

    @Override
    protected void onPause() {
        Log.e(TAG + "onPause", "haha ");
        super.onPause();
    }

    /**
     * 初始化
     */
    private void initView() {
        texTitle = findViewById(R.id.title_text_title);
        texTitle.setText(getString(R.string.shopping_cart));
        btnBack = findViewById(R.id.title_left_button);
        btnBalance = findViewById(R.id.balance);
        checkAll = findViewById(R.id.check_img);
        texTotalMoney = findViewById(R.id.total_money);
        texReceiveAddress = findViewById(R.id.receive_address);
        listview = findViewById(R.id.listview);
        emptyLayout = findViewById(R.id.empty_layout);
        buttomLayout = findViewById(R.id.buttom_layout);
        addressLayout = findViewById(R.id.address_layout);
        emptyLayout.setVisibility(View.GONE);
        buttomLayout.setVisibility(View.GONE);
        addressLayout.setVisibility(View.GONE);
        listview.setAdapter(adapter);
        if (isCallbaclShow) {
            btnBack.setVisibility(View.VISIBLE);
        } else {
            btnBack.setVisibility(View.GONE);
        }
        setListener();
    }

    /**
     * 点击事件
     */
    private void setListener() {
        btnBack.setOnClickListener(this);
        checkAll.setOnClickListener(this);
        btnBalance.setOnClickListener(this);
        texReceiveAddress.setOnClickListener(this);
        listview.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                isCallbaclShow = false;
                checkAll.setImageResource(R.mipmap.nor_check_icon);
                adapter.checkAll(false, false);
                String label = new Date().toLocaleString();
                // 更新显示的label
                refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
                getShopppingCart(false);
            }
        });
        //跳转到
        adapter.setOnItemOnClickListener(new ShoppingCartAdapter.ItemOnClickListener() {
            @Override
            public void onItemOnClickListener(GoodObject goodObject) {
                MallGoodsActivity.jump(ShoppingCartActivity.this, goodObject.getItem_id());
            }
        });
        adapter.setOnCheckListener(new ShoppingCartAdapter.CheckListener() {
            @Override
            public void onCheckListener(ShoppingCartObject shoppingCartObject0) {
                shoppingCartObject = shoppingCartObject0;
                payMoney = shoppingCartObject0.getPayMoney();
//                Log.e("选中商品", shoppingCartObject.getPayMoney() + "");
                orderObject.setMoney(payMoney);
                goodsCount = shoppingCartObject0.getCheckGoodsCount();
                texTotalMoney.setText(String.format ("%.0f",(payMoney * 100)) + "积分");
                if (goodsCount == 0) {
                    btnBalance.setText(getString(R.string.balance));
                } else {
                    btnBalance.setText(getString(R.string.balance) + "(" + goodsCount + ")");
                }
                //当支付金额等于全部商品金额时相当于全选
                if (shoppingCartObject.isCheck()) {
                    isCheckAll = true;
                    checkAll.setImageResource(R.mipmap.sel_check_icon);
                } else {
                    isCheckAll = false;
                    checkAll.setImageResource(R.mipmap.nor_check_icon);
                }

                if (shoppingCartObject.getLisBusinessObject().size() == 0) {//所有商品被删除完后显示空页面
                    showEmpty(true);
                } else {
                    texTitle.setText(getString(R.string.shopping_cart) + "（" + shoppingCartObject.getGoodsCount() + "）");
                }
            }
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.title_left_button:
                finish();
                break;
            case R.id.balance://结算按钮
                if (goodsCount <= 0) {
                    toast(getString(R.string.pls_check_goods));
                    return;
                }
                createOrrder();
                break;
            case R.id.check_img://全选按钮
                if (isCheckAll) {
                    isCheckAll = false;
                    adapter.checkAll(false, true);
                    checkAll.setImageResource(R.mipmap.nor_check_icon);
                } else {
                    isCheckAll = true;
                    adapter.checkAll(true, true);
                    checkAll.setImageResource(R.mipmap.sel_check_icon);
                }
                Log.e("isCheckAll", isCheckAll + "");
                break;
            case R.id.receive_address://地址选择
                AddressManageActivity.jump(ShoppingCartActivity.this);
                break;
        }
    }

    /**
     * 创建订单详情
     */
    private void createOrrder() {
        orderObject.getCarIds().clear();
        orderObject.getTrade_paybillData().clear();
        LoadingUtils.createLoadingDialog(context, "正在生成订单...", true);
        List<BusinessObject> lisBusinessObject = shoppingCartObject.getLisBusinessObject();
        for (int i = 0; i < lisBusinessObject.size(); i++) {//过滤没有选中的商品
            BusinessObject bus = lisBusinessObject.get(i);
            List<GoodObject> lisGoods = bus.getTradeData().getOrderList();
            BusinessObject businessObject = new BusinessObject();
            businessObject.copy(bus);
            businessObject.getTradeData().getOrderList().clear();
            for (GoodObject goods : lisGoods) {
                if (goods.isCheck()) {
                    businessObject.setCheck(true);
                    businessObject.getTradeData().getOrderList().add(goods);
                    orderObject.getCarIds().add(goods.getCartId());
                }
            }
            if (businessObject.isCheck()) {
                orderObject.getTrade_paybillData().add(businessObject);
            }
        }
        for (String carid : orderObject.getCarIds()) {
            Log.e("carid", carid);
        }
        HttpMyOrder.createOrder(token, orderObject.getCarIds(), createGoodsRespose);
    }

    private void showEmpty(boolean isShow) {
        if (isShow) {
            texTitle.setText(getString(R.string.shopping_cart));
            emptyLayout.setVisibility(View.VISIBLE);
            addressLayout.setVisibility(View.GONE);
            buttomLayout.setVisibility(View.GONE);
        } else {
            emptyLayout.setVisibility(View.GONE);
            addressLayout.setVisibility(View.VISIBLE);
            buttomLayout.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 生成订单后跳转到确认订单界面
     */
    private void jumpToConfirmOrder() {
        ConfirmOrderActivity.jumpForResult(ShoppingCartActivity.this, orderObject, addressObject, Globals.REQUSE_CODE_ConfirmOrderActivity);
    }


    /**
     * 获取购物车列表
     */
    private void getShopppingCart(boolean isRefresh) {
//        ShoppingCartPresenter.getInstance().getCartList(Globals.getToken(), new DataResponseListener<ShoppingCartObject>() {
//            @Override
//            public void onSuccess(ShoppingCartObject dataResponse) {
//            }
//
//            @Override
//            public void onFail(String failMessage) {
//
//            }
//
//            @Override
//            public void onError(Throwable e) {
//
//            }
//        });
        if (isRefresh) {
            listview.setRefreshing();
        }
        shoppingCartObject.getLisBusinessObject().clear();
        HttpShopppingCart.getGoodsCartList(token, getShopppingCartRespose);
    }

    /**
     * 获取默认收货地址
     */
    private void getReceiveAddress() {
        HttpShopppingCart.getReceiveAddress(token, getAddressRespose);
    }

    /**
     * 列表接口监听
     */
    AsyncHttpResponseHandler getShopppingCartRespose = new AsyncHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            String result = new String(responseBody);
            Log.e(TAG + "购物车列表", result);
            listview.onRefreshComplete();
            try {
                JSONObject json = new JSONObject(result);
                if (0 == json.optInt("errcode") && 100 == json.optInt("result")) {
                    JSONObject dataObject = json.optJSONObject("data");
                    JSONArray shopArray = dataObject.optJSONArray("shopInfo");
                    JSONArray goodsArray = dataObject.optJSONArray("catrInfo");
                    shoppingCartObject.setShoppingCartTotalMoney(dataObject.optDouble("totalPrice"));
                    if (shopArray != null) {
                        for (int i = 0; i < shopArray.length(); i++) {
                            JSONObject shopObject = shopArray.optJSONObject(i);
                            BusinessObject businessObject = new BusinessObject();//商店对象
                            businessObject.getTradeData().setShop_id(shopObject.optString("shop_id"));
                            businessObject.getTradeData().setShopName(shopObject.optString("shop_name"));
                            shoppingCartObject.getLisBusinessObject().add(businessObject);
                        }
                    }
                    for (int i = 0; i < goodsArray.length(); i++) {
                        JSONObject goodsObject = goodsArray.optJSONObject(i);
                        GoodObject goods = new GoodObject();//商品对象
                        goods.setCartId(goodsObject.optString("cart_id"));
//                        goods.setGoodsTotalPrice(goodsObject.optDouble("goodsTotalPrice"));
                        goods.setPic_path(goodsObject.optString("image_default_id"));
                        goods.setItem_id(goodsObject.optString("item_id"));
                        goods.setPrice(goodsObject.optDouble("price"));
                        goods.setNum(goodsObject.optInt("quantity"));
                        goods.setShop_id(goodsObject.optString("shop_id"));
                        goods.setSku_id(goodsObject.optString("sku_id"));
                        goods.setSpec_info(goodsObject.optString("spec_info"));
                        goods.setTitle(goodsObject.optString("title"));
                        goods.setMkt_price(goodsObject.optDouble("mkt_price"));
                        for (BusinessObject businessObject : shoppingCartObject.getLisBusinessObject()) {
                            if (businessObject.getTradeData().getShop_id().equals(goods.getShop_id())) {
                                businessObject.getTradeData().getOrderList().add(goods);
                            }
                        }
                    }

                    if (shoppingCartObject.getLisBusinessObject().size() != 0) {
                        texTitle.setText(getString(R.string.shopping_cart) + "（" + shoppingCartObject.getGoodsCount() + "）");
                        showEmpty(false);
                    } else {
                        texTitle.setText(getString(R.string.shopping_cart));
                        showEmpty(true);
                    }
                    adapter.notifyDataSetChanged();
                } else {
                    Log.e(TAG + "购物车", "刷新" + shoppingCartObject.getLisBusinessObject().size());
                    if (shoppingCartObject.getLisBusinessObject().size() == 0) {
                        showEmpty(true);
                    } else {
                        showEmpty(false);
                    }
                    if (isToast) {
                        toast(json.optString("msg"));
                    }
                    isToast = true;
                }
            } catch (JSONException e) {
                e.printStackTrace();
                if (shoppingCartObject.getLisBusinessObject().size() == 0) {
                    showEmpty(true);
                } else {
                    showEmpty(false);
                }
                toast("服务器数据格式有误（json解析失败！）");
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
            listview.onRefreshComplete();
        }
    };
    /**
     * 地址接口监听
     */
    AsyncHttpResponseHandler getAddressRespose = new AsyncHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            String result = new String(responseBody);
            Log.e(TAG + "收货地址", result);
            try {
                JSONObject json = new JSONObject(result);
                boolean isNull = true;//地址是否为空
                if (0 == json.optInt("errcode") && 100 == json.optInt("result")) {
                    JSONArray dataArray = json.optJSONArray("data");
                    for (int i = 0; i < dataArray.length(); i++) {
                        JSONObject addressJson = dataArray.optJSONObject(i);
                        String address = addressJson.optString("def_addr");
                        if (!"1".equals(address)) {
                            continue;
                        } else {
                            isNull = false;
                            addressObject.setAddr(addressJson.optString("addr"));
                            addressObject.setAddr_id(addressJson.optString("addr_id"));
                            addressObject.setArea(addressJson.optString("area"));
                            addressObject.setArea_id(addressJson.optString("area_id"));
                            addressObject.setDef_addr(addressJson.optString("def_addr"));
                            addressObject.setMobile(addressJson.optString("mobile"));
                            addressObject.setName(addressJson.optString("name"));
                            addressObject.setUser_id(addressJson.optString("user_id"));
                            addressObject.setZip(addressJson.optString("zip"));
                            texReceiveAddress.setText(addressObject.getArea() + addressObject.getAddr());
                            return;
                        }
                    }
                    if (isNull) {
                        texReceiveAddress.setHint("请选择地址...");
                    } else {
                        texReceiveAddress.setText(addressObject.getArea() + addressObject.getAddr());
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {

        }
    };

    /**
     * 结算按钮（生成订单详情）
     */
    AsyncHttpResponseHandler createGoodsRespose = new AsyncHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            String result = new String(responseBody);
            LoadingUtils.closeDialog();
            Log.e(TAG + "生成订单", result);
            try {
                JSONObject json = new JSONObject(result);
                if (0 == json.optInt("errcode") && 100 == json.optInt("result")) {
                    JSONObject dataObject = json.optJSONObject("data");
                    String area = dataObject.optString("area");
                    double cartTotalPrice = dataObject.optDouble("cartTotalPrice");
                    double shopTotalPrice = dataObject.optDouble("shopTotalPrice");
                    int totalCartDelivery = dataObject.optInt("totalCartDelivery");
                    int totalCartQuantity = dataObject.optInt("totalCartQuantity");
                    int totalCartWeight = dataObject.optInt("totalCartWeight");
                    String itemsSkus = dataObject.optString("itemsSkus");

                    JSONArray cartList = dataObject.optJSONArray("cartList");
                    orderObject.getItemIds().clear();
                    orderObject.getSkuIds().clear();
                    for (int i = 0; i < cartList.length(); i++) {
                        JSONObject cartListObject = cartList.optJSONObject(i);
                        String cart_id = cartListObject.optString("cart_id");
                        String goodsTotalPrice = cartListObject.optString("goodsTotalPrice");
                        String image_default_id = cartListObject.optString("image_default_id");
                        String itemStatus = cartListObject.optString("itemStatus");
                        String item_id = cartListObject.optString("item_id");
                        double price = cartListObject.optDouble("price");
                        int quantity = cartListObject.optInt("quantity");
                        String shop_id = cartListObject.optString("shop_id");
                        String sku_id = cartListObject.optString("sku_id");
                        String spec_info = cartListObject.optString("spec_info");
                        String store = cartListObject.optString("store");
                        String title = cartListObject.optString("title");
                        String weight = cartListObject.optString("weight");
                        orderObject.getCarIds().add(cart_id);
                        orderObject.getItemIds().add(item_id);
                        orderObject.getSkuIds().add(sku_id);
                    }
                    JSONArray itemsSkusNew = dataObject.optJSONArray("itemsSkusNew");
                    for (int i = 0; i < itemsSkusNew.length(); i++) {
                        JSONObject itemsSkusNewObject = cartList.optJSONObject(i);
                        String itemId = itemsSkusNewObject.optString("itemId");
                        int num = itemsSkusNewObject.optInt("num");
                        String skuId = itemsSkusNewObject.optString("skuId");
                    }
                    JSONArray shopList = dataObject.optJSONArray("shopList");
                    orderObject.getShopIds().clear();
                    orderObject.getDlytmplIds().clear();
                    orderObject.getPostFees().clear();

                    for (int i = 0; i < shopList.length(); i++) {
                        JSONObject shopListObject = shopList.optJSONObject(i);
                        int delivery = shopListObject.optInt("delivery");
                        double postFree = shopListObject.optInt("postFree");
                        int totalNum = shopListObject.optInt("totalNum");
                        String shop_id = shopListObject.optString("shop_id");
                        String qq = shopListObject.optString("qq");
                        String shop_logo = shopListObject.optString("shop_logo");
                        String shop_name = shopListObject.optString("shop_name");
                        String shopuser_name = shopListObject.optString("shopuser_name");
                        String template_id = shopListObject.optString("template_id");
                        String wangwang = shopListObject.optString("wangwang");
                        double totalEndPrice = shopListObject.optDouble("totalEndPrice");
                        double totalPrice = shopListObject.optDouble("totalPrice");
                        double totalWeight = shopListObject.optDouble("totalWeight");
                        orderObject.getShopIds().add(shop_id);
                        orderObject.getDlytmplIds().add(template_id);
                        orderObject.getPostFees().add(postFree + "");
                        //设置邮费
                        orderObject.getTrade_paybillData().get(i).getTradeData().setPost_fee(postFree);
                    }
                    JSONObject defAddrInfo = dataObject.optJSONObject("defAddrInfo");
                    String addr = defAddrInfo.optString("addr");
                    String addr_id = defAddrInfo.optString("addr_id");
                    String areaID = defAddrInfo.optString("areaID");
                    String def_addr = defAddrInfo.optString("def_addr");
                    String mobile = defAddrInfo.optString("mobile");
                    String name = defAddrInfo.optString("name");
                    String user_id = defAddrInfo.optString("user_id");
                    String zip = defAddrInfo.optString("zip");
                    //----------------------创建成功后跳转到确认订单界面，然后把商品全变成未选状态---------------------
                    jumpToConfirmOrder();
                    adapter.checkAll(false, true);
                } else {
                    LoadingUtils.closeDialog();
                    String msg = json.optString("msg");
                    toast(msg);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
            LoadingUtils.closeDialog();
            toast(getString(R.string.network_or_server_exception));
        }
    };


    //-----------------------------选择地址广播处理-----------------------------
    private void regisBrocastReciver() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Globals.ACTION_UPADDRESS);
        intentFilter.addAction(Globals.ACTION_UP_UI);
        registerReceiver(receiver, intentFilter);
    }

    BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.e(TAG + "收到广播", "更新UI");
            if (intent.getAction().equals(Globals.ACTION_UPADDRESS)) {
                getReceiveAddress();
            } else if (intent.getAction().equals(Globals.ACTION_UP_UI)) {
                isToast = false;
                listview.setRefreshing();
            }
        }
    };
}
